﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using NBA.DataAccess;
using NBA.Entity;
using JJY.CommonHelper;
using System.Web;

namespace NBA.Business
{
    public class MatchListMonitor4ChinaNba
    {
        private const string DOMAINNAME = "http://china.nba.com";
        private const string DATADETAILS = "详细数据";
        private const string PREVIEW = "比赛前瞻";
        private static DaTeamInfo daTeamInfo = new DaTeamInfo();
        private static DaMatchInfo daMatchInfo = new DaMatchInfo();
        private static DaMatchTeamData daMatchTeamData = new DaMatchTeamData();

        public static int ReadMatchList(string urlMatchList)
        {
            int result = 0;
            string strMatchList =
                HttpUtility.HtmlDecode(HttpRequestService.GetHtmlSourceByUrl(urlMatchList, Encoding.UTF8)
                .HtmlToString().Trim().ToUTF8());
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strMatchList);
            HtmlNodeCollection nodeMatchList =
                doc.DocumentNode.SelectNodes("//span[@class='boxscore link']/a");

            Dictionary<string, int> dicUrl = new Dictionary<string, int>();

            if (nodeMatchList != null)
            {
                foreach (HtmlNode htmlNode in nodeMatchList)
                {
                    if (htmlNode.InnerText.ReplaceEmpty() == DATADETAILS)
                    {
                        string url = htmlNode.Attributes["href"].Value;
                        if (!dicUrl.ContainsKey(url))
                        {
                            if (ReadMatch(url))
                            {
                                result++;
                                dicUrl.Add(url, 1);
                            }
                        }
                    }
                }
            }

            HtmlNodeCollection nodePreviewList =
                doc.DocumentNode.SelectNodes("//span[@class='preview link']/a");
            int year = int.Parse(doc.DocumentNode
                .SelectSingleNode("//span[@class='dateHeader']").InnerText.Split('-')[0]);
            if (nodePreviewList != null)
            {
                foreach (HtmlNode htmlNode in nodePreviewList)
                {
                    if (htmlNode.InnerText.ReplaceEmpty() == PREVIEW)
                    {
                        string url = htmlNode.Attributes["href"].Value;
                        if (!dicUrl.ContainsKey(url))
                        {
                            if (ReadPrev(url, year))
                            {
                                result++;
                                dicUrl.Add(url, 1);
                            }
                        }
                    }
                }
            }
            return result;
        }

        private static bool ReadPrev(string urlPreview, int year)
        {
            bool result = false;

            string strPreview =
                HttpUtility.HtmlDecode(HttpRequestService.GetHtmlSourceByUrl(DOMAINNAME + urlPreview,
                Encoding.UTF8).HtmlToString().Trim().ToUTF8());
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strPreview);

            HtmlNodeCollection nodeTeamNameSet =
                doc.DocumentNode.SelectNodes("//span[@class='name']");
            
            Guid visitingTeamInfoId = InsertTeamName(nodeTeamNameSet[0].InnerText.Trim());
            Guid homeTeamId = InsertTeamName(nodeTeamNameSet[1].InnerText.Trim());

            DateTime date = DateTime.Parse(year + "-" + doc.DocumentNode.SelectSingleNode("//div[@class='date']")
                .InnerText.Split(',')[1].Trim().Replace("月", "-").Replace("日", string.Empty));
            
            MatchInfo matchInfo = new MatchInfo()
            {
                MatchDateTime = date,
                VisitingTeamId = visitingTeamInfoId,
                HomeTeamId = homeTeamId,
                SeasonYear = 2011,
                VisitingFirst = 0,
                VisitingSecond = 0,
                VisitingThird = 0,
                VisitingFourth = 0,
                VisitingScore = 0,
                VisitingOt = 0,
                HomeFirst = 0,
                HomeSecond = 0,
                HomeThird = 0,
                HomeFourth = 0,
                HomeScore = 0,
                HomeOt = 0,
                OtCount = 0
            };
            daMatchInfo.InsertOrUpdate(matchInfo);

            result = true;
            return result;
        }

        private static Guid InsertTeamName(string teamName)
        {
            Guid result = Guid.NewGuid();
            TeamInfo teamInfo = new TeamInfo()
            {
                TeamId = Guid.NewGuid(),
                LocalName = teamName.IndexOf(" ") > 0 ? teamName.Split(' ')[0] : string.Empty,
                TeamName = teamName.IndexOf(" ") > 0 ? teamName.Split(' ')[1] : string.Empty,
                TeamFullName = teamName.ReplaceEmpty()
            };

            result = daTeamInfo.InsertOrUpdate(teamInfo);
            return result;
        }

        private static bool ReadMatch(string urlMatch)
        {
            bool result = false;

            string strMatchInfo =
                HttpUtility.HtmlDecode(HttpRequestService.GetHtmlSourceByUrl(DOMAINNAME + urlMatch, 
                Encoding.UTF8).HtmlToString().Trim().ToUTF8());

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(strMatchInfo);

            Guid visitingTeamId;
            Guid homeTeamId;
            Guid matchId;
            ReadMatchBasicData(doc, out matchId, out visitingTeamId, out homeTeamId);

            ReadTeamDataDetails(doc, matchId, visitingTeamId, homeTeamId);

            result = true;

            return result;
        }

        private static bool ReadTeamDataDetails(HtmlDocument doc, Guid matchId,
            Guid visitingTeamId, Guid homeTeamId)
        {
            bool result = false;

            HtmlNodeCollection nodeTdTotal = doc.DocumentNode.SelectNodes("//tr[@class='even total']/td");

            MatchTeamData visitingMatchTeamData = new MatchTeamData();
            MatchTeamData homeMatchTeamData = new MatchTeamData();

            if (nodeTdTotal.Count == 34)
            {
                short visitingTotalShot = short.Parse(nodeTdTotal[3].InnerText.Split('-')[1].Trim());
                short visitingTotalGoal = short.Parse(nodeTdTotal[3].InnerText.Split('-')[0].Trim());
                short visitingShot3 = short.Parse(nodeTdTotal[4].InnerText.Split('-')[1].Trim());
                short visitingShot3Goal = short.Parse(nodeTdTotal[4].InnerText.Split('-')[0].Trim());
                short visitingFreeThrow = short.Parse(nodeTdTotal[5].InnerText.Split('-')[1].Trim());
                short visitingFreeThrowGoal = short.Parse(nodeTdTotal[5].InnerText.Split('-')[0].Trim());
                visitingMatchTeamData.IsAtHome = false;
                visitingMatchTeamData.MatchId = matchId;
                visitingMatchTeamData.TeamId = visitingTeamId;
                visitingMatchTeamData.Shot3 = visitingShot3;
                visitingMatchTeamData.Goal3 = visitingShot3Goal;
                visitingMatchTeamData.Shot2 = (short)(visitingTotalShot - visitingShot3);
                visitingMatchTeamData.Goal2 = (short)(visitingTotalGoal - visitingShot3Goal);
                visitingMatchTeamData.FreeThrow = visitingFreeThrow;
                visitingMatchTeamData.FreeThrowGoal = visitingFreeThrowGoal;
                visitingMatchTeamData.OffensiveRebound = short.Parse(nodeTdTotal[7].InnerText.Trim());
                visitingMatchTeamData.DefensiveRebound = short.Parse(nodeTdTotal[8].InnerText.Trim());
                visitingMatchTeamData.Assist = short.Parse(nodeTdTotal[10].InnerText.Trim());
                visitingMatchTeamData.Foul = short.Parse(nodeTdTotal[11].InnerText.Trim());
                visitingMatchTeamData.Steal = short.Parse(nodeTdTotal[12].InnerText.Trim());
                visitingMatchTeamData.Turnover = short.Parse(nodeTdTotal[13].InnerText.Trim());
                visitingMatchTeamData.Block = short.Parse(nodeTdTotal[14].InnerText.Trim());
                visitingMatchTeamData.Scoring = short.Parse(nodeTdTotal[15].InnerText.Trim());

                short homeTotalShot = short.Parse(nodeTdTotal[20].InnerText.Split('-')[1].Trim());
                short homeTotalGoal = short.Parse(nodeTdTotal[20].InnerText.Split('-')[0].Trim());
                short homeShot3 = short.Parse(nodeTdTotal[21].InnerText.Split('-')[1].Trim());
                short homeShot3Goal = short.Parse(nodeTdTotal[21].InnerText.Split('-')[0].Trim());
                short homeFreeThrow = short.Parse(nodeTdTotal[22].InnerText.Split('-')[1].Trim());
                short homeFreeThrowGoal = short.Parse(nodeTdTotal[22].InnerText.Split('-')[0].Trim());
                homeMatchTeamData.IsAtHome = true;
                homeMatchTeamData.MatchId = matchId;
                homeMatchTeamData.TeamId = homeTeamId;
                homeMatchTeamData.Shot3 = homeShot3;
                homeMatchTeamData.Goal3 = homeShot3Goal;
                homeMatchTeamData.Shot2 = (short)(homeTotalShot - homeShot3);
                homeMatchTeamData.Goal2 = (short)(homeTotalGoal - homeShot3Goal);
                homeMatchTeamData.FreeThrow = homeFreeThrow;
                homeMatchTeamData.FreeThrowGoal = homeFreeThrowGoal;
                homeMatchTeamData.OffensiveRebound = short.Parse(nodeTdTotal[24].InnerText.Trim());
                homeMatchTeamData.DefensiveRebound = short.Parse(nodeTdTotal[25].InnerText.Trim());
                homeMatchTeamData.Assist = short.Parse(nodeTdTotal[27].InnerText.Trim());
                homeMatchTeamData.Foul = short.Parse(nodeTdTotal[28].InnerText.Trim());
                homeMatchTeamData.Steal = short.Parse(nodeTdTotal[29].InnerText.Trim());
                homeMatchTeamData.Turnover = short.Parse(nodeTdTotal[30].InnerText.Trim());
                homeMatchTeamData.Block = short.Parse(nodeTdTotal[31].InnerText.Trim());
                homeMatchTeamData.Scoring = short.Parse(nodeTdTotal[32].InnerText.Trim());
            }

            if (daMatchTeamData.InsertOrUpdate(visitingMatchTeamData) > 0
                && daMatchTeamData.InsertOrUpdate(homeMatchTeamData) > 0)
            {
                result = true;
            }

            return result;
        }

        private static bool ReadMatchBasicData(HtmlDocument doc, out Guid matchId, 
            out Guid visitingTeamId, out Guid homeTeamId)
        {
            bool result = false;

            HtmlNodeCollection nodeTeamNameSet =
                doc.DocumentNode.SelectNodes("//td[@class='titleText teamHeader']");

            visitingTeamId = InsertTeamName(nodeTeamNameSet[0].InnerText.Trim());
            homeTeamId = InsertTeamName(nodeTeamNameSet[1].InnerText.Trim());

            HtmlNode nodeTeamDate = doc.DocumentNode.SelectSingleNode("//div[@class='gameDate']");
            HtmlNode nodeScoreTable = doc.DocumentNode.SelectSingleNode("//table[@class='scoreBreakDownContainer']");
            HtmlNodeCollection nodeVisitingScore =
                doc.DocumentNode.SelectNodes(nodeScoreTable.XPath + "/tr[@class='odd']/td");
            HtmlNodeCollection nodeHomeScore =
                doc.DocumentNode.SelectNodes(nodeScoreTable.XPath + "/tr[@class='even']/td");

            short visitingOt = 0;
            short homeOt = 0;
            if (nodeVisitingScore.Count > 6)
            {
                for (int i = 5; i < nodeVisitingScore.Count - 1; i++)
                {
                    visitingOt += short.Parse(nodeVisitingScore[i].InnerText);
                    homeOt += short.Parse(nodeHomeScore[i].InnerText);
                }
            }

            MatchInfo matchInfo = new MatchInfo()
            {
                MatchDateTime = DateTime.Parse(nodeTeamDate.InnerText),
                VisitingTeamId = visitingTeamId,
                HomeTeamId = homeTeamId,
                SeasonYear = 2011,
                VisitingFirst = short.Parse(nodeVisitingScore[1].InnerText),
                VisitingSecond = short.Parse(nodeVisitingScore[2].InnerText),
                VisitingThird = short.Parse(nodeVisitingScore[3].InnerText),
                VisitingFourth = short.Parse(nodeVisitingScore[4].InnerText),
                VisitingScore = short.Parse(nodeVisitingScore[nodeVisitingScore.Count - 1].InnerText),
                VisitingOt = visitingOt,
                HomeFirst = short.Parse(nodeHomeScore[1].InnerText),
                HomeSecond = short.Parse(nodeHomeScore[2].InnerText),
                HomeThird = short.Parse(nodeHomeScore[3].InnerText),
                HomeFourth = short.Parse(nodeHomeScore[4].InnerText),
                HomeScore = short.Parse(nodeHomeScore[nodeHomeScore.Count - 1].InnerText),
                HomeOt = homeOt,
                OtCount = (byte)(nodeVisitingScore.Count - 6)
            };

                matchId = daMatchInfo.InsertOrUpdate(matchInfo);

            return result;
        }
    }
}
